package com.simple.cms.core.shiro;

import com.alibaba.fastjson.JSON;
import com.simple.cms.common.enums.ResultCode;
import com.simple.cms.common.result.CommonResult;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.http.MediaType;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;

/**
 * @author kin
 * @since 2017/8/11
 */
public class StatelessAuthFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        String authority = httpRequest.getHeader("Authorization");

        StatelessToken token = new StatelessToken("123", authority);

        try {
            getSubject(servletRequest, servletResponse).login(token);
        } catch (CredentialsException e) {
            out(servletResponse, ResultCode.INVALID_TOKEN);
            return false;
        }

        return true;
    }


    public static void out(ServletResponse response, ResultCode resultCode) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            out = response.getWriter();
            out.println(JSON.toJSONString(new CommonResult(resultCode.getCode(), resultCode.getMsg())));
        } catch (Exception ignored) {

        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }
}
